package com.bawei.fuxi.ui.zhibo;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;
import top.littlefogcat.danmakulib.danmaku.Danmaku;
import top.littlefogcat.danmakulib.danmaku.DanmakuManager;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.alipay.sdk.app.EnvUtils;
import com.alipay.sdk.app.PayTask;
import com.bawei.fuxi.R;
import com.bawei.fuxi.base.mvp.BaseActivity;
import com.bawei.fuxi.base.mvp.BasePresenter;
import com.bawei.fuxi.base.utils.GlideUtils;
import com.bawei.fuxi.entity.GiftEntity;
import com.bawei.fuxi.entity.MessageEntity;
import com.bawei.fuxi.entity.VideoEntity;
import com.bawei.fuxi.pay.PayResult;
import com.bawei.fuxi.pay.util.OrderInfoUtil2_0;
import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.hyphenate.EMMessageListener;
import com.hyphenate.EMValueCallBack;
import com.hyphenate.chat.EMChatRoom;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.chat.EMTextMessageBody;
import com.hyphenate.chat.adapter.EMABase;
import com.kaisengao.likeview.like.KsgLikeView;
import com.shuyu.gsyvideoplayer.video.StandardGSYVideoPlayer;

import java.util.List;
import java.util.Map;

//发送礼物前：判断余额是否充足--》网络请求更新余额--》发送动画
//充值：支付宝支付成功后--》网络请求更新余额
//环信：加入聊天室 退出聊天室
@Route(path = "/app/zhibo")
public class ZhiBoActivity extends BaseActivity<ZhiBoContract.IZhiBoView,ZhiBoPresenter> implements ZhiBoContract.IZhiBoView {
    @Autowired
    VideoEntity.DataBean video;

    private ConstraintLayout clZhibo;
    private StandardGSYVideoPlayer gsy;
    private ImageView ivUser;
    private TextView tvUsername;
    private TextView tvDianzanCount;
    private TextView tvGuanzhu;
    private KsgLikeView ksgView;
    private LinearLayout llBottom;
    private EditText etInput;
    private ImageView ivSend;
    private ImageView ivFull;
    private ImageView ivCar;
    private ImageView ivGift;
    private ImageView ivDianzan;
    private ConstraintLayout clGift;
    private TextView tvMoney;
    private RecyclerView rvGift;
    private GiftAdapter mGiftAdapter;
    private ImageView ivGiftSelect;
    private TextView tvGiftName;
    private RecyclerView rvChat;
    private MessageAdapter mMessageAdapter;
    private FrameLayout danmuView;//弹幕
    private  GiftEntity.DataBean gift;//选中的礼物
    private float money = 1000;//默认余额
    private String chatRoomId = "211150599946242";//聊天室id
    //接受消息的监听
    EMMessageListener msgListener = new EMMessageListener() {

        // 收到消息，遍历消息队列，解析和显示。
        @Override
        public void onMessageReceived(List<EMMessage> messages) {
            runOnUiThread(new Runnable() {//切换到主线程
                @Override
                public void run() {
                    for (EMMessage message : messages) {
                        String from = message.getFrom();//来自谁
                        EMTextMessageBody textMessageBody = (EMTextMessageBody) message.getBody();//文本消息体
                        String text = textMessageBody.getMessage();//消息的内容
                        //将消息显示在列表中
                        MessageEntity messageEntity = new MessageEntity(from, text);
                        mMessageAdapter.getData().add(messageEntity);
                        mMessageAdapter.notifyDataSetChanged();
                        rvChat.scrollToPosition(mMessageAdapter.getData().size()-1);//滚动到最新一条
                    }
                }
            });

        }
    };

    @Override
    public int bindLayout() {
        return R.layout.activity_zhi_bo;
    }

    @Override
    public void initView(Bundle savedInstanceState) {
        ARouter.getInstance().inject(this);
        Toast.makeText(this, ""+video.getCaption(), Toast.LENGTH_SHORT).show();
        clZhibo = (ConstraintLayout) findViewById(R.id.cl_zhibo);
        gsy = (StandardGSYVideoPlayer) findViewById(R.id.gsy);
        ivUser = (ImageView) findViewById(R.id.iv_user);
        tvUsername = (TextView) findViewById(R.id.tv_username);
        tvDianzanCount = (TextView) findViewById(R.id.tv_dianzan_count);
        tvGuanzhu = (TextView) findViewById(R.id.tv_guanzhu);
        ksgView = (KsgLikeView) findViewById(R.id.ksg_view);
        llBottom = (LinearLayout) findViewById(R.id.ll_bottom);
        etInput = (EditText) findViewById(R.id.et_input);
        ivSend = (ImageView) findViewById(R.id.iv_send);
        ivFull = (ImageView) findViewById(R.id.iv_full);
        ivCar = (ImageView) findViewById(R.id.iv_car);
        ivGift = (ImageView) findViewById(R.id.iv_gift);
        ivDianzan = (ImageView) findViewById(R.id.iv_dianzan);
        clGift = (ConstraintLayout) findViewById(R.id.cl_gift);
        tvMoney = (TextView) findViewById(R.id.tv_money);
        rvGift = (RecyclerView) findViewById(R.id.rv_gift);
        ivGiftSelect = (ImageView) findViewById(R.id.iv_gift_select);
        tvGiftName = (TextView) findViewById(R.id.tv_gift_name);
        rvChat = (RecyclerView) findViewById(R.id.rv_chat);
        danmuView = (FrameLayout) findViewById(R.id.danmu_view);
        initGsy();//初始化视频频
        initUser();//初始化用户信息左上角
        initGift();//初始化礼物列表
        initMessage();//初始化聊天列表
        initRoom();//加入聊天室
    }

    private void initRoom() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                // 加入聊天室
                EMClient.getInstance().chatroomManager().joinChatRoom(chatRoomId, new EMValueCallBack<EMChatRoom>() {
                    @Override
                    public void onSuccess(EMChatRoom value) {
                        // 注册消息监听
                        EMClient.getInstance().chatManager().addMessageListener(msgListener);

                    }

                    @Override
                    public void onError(int error, String errorMsg) {

                    }
                });
            }
        }).start();
    }
    //退出聊天室
    @Override
    protected void onDestroy() {
        super.onDestroy();

        new Thread(new Runnable() {
            @Override
            public void run() {
                EMClient.getInstance().chatroomManager().leaveChatRoom(chatRoomId);
                // 解注册消息监听
                EMClient.getInstance().chatManager().removeMessageListener(msgListener);
            }
        }).start();
    }

    private void initMessage() {
        mMessageAdapter = new MessageAdapter(R.layout.item_message);
        rvChat.setAdapter(mMessageAdapter);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setStackFromEnd(true);//从下向上滚动
        rvChat.setLayoutManager(linearLayoutManager);
    }

    private void initGsy() {
        gsy.setUp(video.getVideopath(),true,"");
        gsy.getBackButton().setVisibility(View.GONE);
        gsy.startPlayLogic();
    }

    private void initGift() {
        mGiftAdapter = new GiftAdapter(R.layout.item_gift);
        rvGift.setAdapter(mGiftAdapter);
        rvGift.setLayoutManager(new StaggeredGridLayoutManager(4,StaggeredGridLayoutManager.VERTICAL));
        //item的点击
        mGiftAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
                gift = mGiftAdapter.getData().get(position);
                GlideUtils.getInstance().loadImage(ZhiBoActivity.this,gift.getGiftpath(),ivGiftSelect);
                tvGiftName.setText(gift.getGiftname()+"");
            }
        });
    }

    @Override
    public ZhiBoPresenter createPresenter() {
        return new ZhiBoPresenter();
    }

    //初始化用户信息左上角
    private void initUser() {
        tvUsername.setText(video.getAuthname()+"");
        GlideUtils.getInstance().loadCircleImage(this,video.getVideopath(),ivUser);
    }
    @Override
    public void initData() {

    }
    //点击事件：点赞
    public void dianzan(View view) {
        ksgView.addLikeImages(R.drawable.ic_xihuanred,R.drawable.ic_add,R.drawable.ic_bofang);
        ksgView.addFavor();
    }
    //点击事件：弹出礼物框+请求礼物数据展示
    public void showgift(View view) {
        clGift.setVisibility(View.VISIBLE);
        mPresenter.gift();
    }
    //点击事件：发送礼物
    public void sendGift(View view) {
        //0：判断钱够嘛
        if(money < gift.getPrice()){
            Toast.makeText(this, "不够你个穷鬼", Toast.LENGTH_SHORT).show();
            return;
        }else{
            money -= gift.getPrice();
            tvMoney.setText("余额："+money);
        }
        //1：ImageView对象
        ImageView imageView = new ImageView(this);
        FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(200, 200);//宽度高度
        imageView.setLayoutParams(layoutParams);
        GlideUtils.getInstance().loadImage(this,gift.getGiftpath(),imageView);
        //2:添加到容器中
        clZhibo.addView(imageView);
        //3：动画效果
        ObjectAnimator TranslationY = ObjectAnimator.ofFloat(imageView, "TranslationY", 0, 300);
        ObjectAnimator TranslationX = ObjectAnimator.ofFloat(imageView, "TranslationX", 0, 300);
        ObjectAnimator rotation = ObjectAnimator.ofFloat(imageView, "Rotation", 0, 360);
        AnimatorSet animatorSet = new AnimatorSet();
        animatorSet.playTogether(TranslationY,TranslationX,rotation);
        animatorSet.setDuration(2000);
        animatorSet.start();
        //4:动画结束移除ImageView+礼物框消失
        animatorSet.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                clZhibo.removeView(imageView);
                clGift.setVisibility(View.GONE);
            }
        });
    }
    //点击事件：发送消息+发送弹幕+环信发消息
    public void sendMessage(View view) {
        //发送消息
        String s = etInput.getText().toString();
        String currentUser = EMClient.getInstance().getCurrentUser();//当前用户名
        MessageEntity messageEntity = new MessageEntity(currentUser, s);
        mMessageAdapter.getData().add(messageEntity);
        mMessageAdapter.notifyDataSetChanged();
        rvChat.scrollToPosition(mMessageAdapter.getData().size()-1);//自动滚到最新的一条

        //发送弹幕
        DanmakuManager.getInstance().init(this,danmuView);//吃屎话
        Danmaku danmaku = new Danmaku();
        danmaku.text = s;
        danmaku.color = "#E91E63";
        danmaku.size = 50;
        DanmakuManager.getInstance().send(danmaku);//发送弹幕
        //环信发送消息
        // 创建一条文本消息，`content` 为消息文字内容，`toChatUsername` 为对方用户或者群聊的 ID，后文皆是如此。
        EMMessage message = EMMessage.createTxtSendMessage(s, chatRoomId);
// 设置消息类型，即设置 `Message` 类的 `ChatType` 属性，可设置为 `Chat`、`GroupChat` 和 `ChatRoom`，即单聊，群聊或聊天室消息，默认为单聊。
        message.setChatType(EMMessage.ChatType.ChatRoom);

    }
    //点击事件集成支付宝--》支付成功更新钱
    public void zhifu(View view) {
        EnvUtils.setEnv(EnvUtils.EnvEnum.SANDBOX);
        pay();
    }
    //展示礼物列表
    @Override
    public void showGift(GiftEntity giftEntity) {
        if(giftEntity != null && giftEntity.getCode() == 200){
            mGiftAdapter.getData().addAll(giftEntity.getData());
            mGiftAdapter.notifyDataSetChanged();
        }
    }



    /**
     * 用于支付宝支付业务的入参 app_id。
     */
    public static final String APPID =
            "2016103000779553";

    /**
     * 用于支付宝账户登录授权业务的入参 pid。
     */
    public static final String PID = "";

    /**
     * 用于支付宝账户登录授权业务的入参 target_id。
     */
    public static final String TARGET_ID = "";

    /**
     * pkcs8 格式的商户私钥。
     * <p>
     * 如下私钥，RSA2_PRIVATE 或者 RSA_PRIVATE 只需要填入一个，如果两个都设置了，本 Demo 将优先
     * 使用 RSA2_PRIVATE。RSA2_PRIVATE 可以保证商户交易在更加安全的环境下进行，建议商户使用
     * RSA2_PRIVATE。
     * <p>
     * 建议使用支付宝提供的公私钥生成工具生成和获取 RSA2_PRIVATE。
     * 工具地址：https://doc.open.alipay.com/docs/doc.htm?treeId=291&articleId=106097&docType=1
     */
    public static final String RSA2_PRIVATE = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCYJYflUySpQ//IL3wxdS937UV3iUw2VFXSYfq60DjS3/m73nM23uddswvuRoO+822JuekiXbfvkmGWYXNdXKqAoempPIl+ADxEXqvYGioyMLqVqV1meVQkGfVSr+CxQ9rkmdkVaKWqqDrVeFcUlN9ceW8YLJiKhpBT6hhqFPh7pngLIm6EotQ3mMNZoRID4yXpu8p6Eo8468Xr7mQZhfqGkjnXUWlhewBItZWdQ9JcwEsWsRUtCmk/BbAO+H7NrVv2oWREIacoKD0Ws79cAmdhQw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9YJAjavNpGuJE1W4AcfJtjDht4uoQn6ZdMkCgYEAyR+e/PfxPevjzGmIBLZ+ZXnR1SVlQwda4/GrUyllUWf7akTSLkT+VvkfbcHaHB2Vil8LFYt/SKteKPBy7l0YRuNq74FLZka6Y6OmmemHXRSqOJzcEGyrOWT5ElLmywMltQK4s0VXwTAtsForDE4eqmuz1rZ0Er4rsKdVpdu/I5A=";
    public static final String RSA_PRIVATE = "";

    private static final int SDK_PAY_FLAG = 1;
    private static final int SDK_AUTH_FLAG = 2;

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     * 对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
//                        ToastUtils.showShort("支付成功");
                        Toast.makeText(ZhiBoActivity.this, "支付成功", Toast.LENGTH_SHORT).show();
                        money+=1000;
                        tvMoney.setText("余额"+money+"");
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
//                        ToastUtils.showShort("支付失败" + payResult);
                        Toast.makeText(ZhiBoActivity.this, "支付失败", Toast.LENGTH_SHORT).show();
                    }
                    break;
                }

                default:
                    break;
            }
        }

        ;
    };

    /**
     * 支付宝支付业务示例
     */
    public void pay() {
        if (TextUtils.isEmpty(APPID) || (TextUtils.isEmpty(RSA2_PRIVATE) && TextUtils.isEmpty(RSA_PRIVATE))) {
            return;
        }

        /*
         * 这里只是为了方便直接向商户展示支付宝的整个支付流程；所以Demo中加签过程直接放在客户端完成；
         * 真实App里，privateKey等数据严禁放在客户端，加签过程务必要放在服务端完成；
         * 防止商户私密数据泄露，造成不必要的资金损失，及面临各种安全风险；
         *
         * orderInfo 的获取必须来自服务端；
         */
        boolean rsa2 = (RSA2_PRIVATE.length() > 0);
        Map<String, String> params = OrderInfoUtil2_0.buildOrderParamMap(APPID, rsa2);
        String orderParam = OrderInfoUtil2_0.buildOrderParam(params);

        String privateKey = rsa2 ? RSA2_PRIVATE : RSA_PRIVATE;
        String sign = OrderInfoUtil2_0.getSign(params, privateKey, rsa2);
        final String orderInfo = orderParam + "&" + sign;

        final Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                PayTask alipay = new PayTask(ZhiBoActivity.this);
                Map<String, String> result = alipay.payV2(orderInfo, true);
                Log.i("msp", result.toString());

                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }
}